from flask import Flask
from flask_cors import CORS
from src.api.system import system_blueprint
from src.api.test import test_blueprint
from src.api.user import user_blueprint
from src.common import result
from src.api.deployment_api import deployment_blueprint
import os
import json
import werkzeug.exceptions
import traceback

env_active = os.environ.get('AIDES_ENV', 'local')

context_path = 'api'

app = Flask(__name__)

app.config.from_file(f"{app.root_path}/envs/config_{env_active}.json", load=json.load)

app.register_blueprint(system_blueprint, url_prefix=f"/{context_path}/{system_blueprint.name}")
app.register_blueprint(test_blueprint, url_prefix=f"/{context_path}/{test_blueprint.name}")
app.register_blueprint(user_blueprint, url_prefix=f"/{context_path}/{user_blueprint.name}")
app.register_blueprint(deployment_blueprint, url_prefix=f"/{context_path}/{deployment_blueprint.name}")
CORS(app, supports_credentials=True)


# 全局错误处理
@app.errorhandler(werkzeug.exceptions.HTTPException)
def handle_http_exception(e):
    app.logger.error(traceback.format_exc())
    return result.fail(e.description)


@app.errorhandler(Exception)
def handle_exception(e):
    # 如果是 HTTPException，已经处理过了
    if isinstance(e, werkzeug.exceptions.HTTPException):
        return handle_http_exception(e)

    # 其他类型的异常
    app.logger.error(traceback.format_exc())
    return result.fail(str(e))


if __name__ == '__main__':
    app.run()
